package com.umessage.hotel.rest;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.umessage.hotel.domain.RoomStatus;
import com.umessage.hotel.model.RoomModel;
import com.umessage.hotel.service.RoomInfoService;
import com.umessage.hotel.service.RoomStatusService;
import com.umessage.hotel.util.RestResult;
import com.umessage.hotel.util.RestResultGenerator;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api("房间管理")
@RestController
@RequestMapping(value = "/rest/rooms")
public class RoomResource {

	@Autowired
	private RoomInfoService roomService;
	@Autowired
	private RoomStatusService roomStatusService;
	/**
	 * 获取房间信息
	 * 
	 * @param orderId
	 * @return
	 */
	@ApiOperation(value = "获取房间列表", notes = "获取房间列表（小程序）")
	@RequestMapping(method = RequestMethod.GET)
public RestResult<List<RoomModel>> listRooms(ServletRequest request,@RequestParam(required=true)String hotelId,@RequestParam(required=true)String endTimeStr,
		@RequestParam(required=true)String beginTimeStr,@RequestParam(required=true)String type) {
		try {
			//roomsType=1 列表访问接口  roomsType=null 房间详情访问详情
			String roomsType=type;
			String memberId = (String) request.getAttribute("subject");
			if(hotelId!=null) {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			Date beginTime=sdf.parse(beginTimeStr);
			Date endTime=sdf.parse(endTimeStr);
			List<RoomModel> listRooms = this.roomService.listRooms(hotelId, beginTime, endTime,memberId,roomsType);
			return RestResultGenerator.genSuccessResult(listRooms);
			}else {
				return RestResultGenerator.genSuccessResult(new ArrayList<RoomModel>());
			}
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult("error");
		}
	}

	

	/**
	 * 获取单个房间信息
	 * 
	 * @param orderId
	 * @return
	 * @throws ParseException 
	 */
	@ApiOperation(value = "获取单个房间的信息", notes = "获取单个房间的信息")
	@RequestMapping(value = "/getRoomInfo", method = RequestMethod.GET)
	public RestResult<RoomModel> loadRoom(ServletRequest request,@RequestParam(required=true)String roomId,@RequestParam(required=true)String endTimeStr,@RequestParam(required=true)String beginTimeStr) {
		try {
			String memberId = (String) request.getAttribute("subject");
			String hotelId = (String) request.getAttribute("issuer");
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			Date beginTime=sdf.parse(beginTimeStr);
			Date endTime=sdf.parse(endTimeStr);
			RoomModel roomModel = this.roomService.loadRoom(hotelId, roomId, endTime, beginTime, memberId);
			return RestResultGenerator.genSuccessResult(roomModel);
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult("invalid params");
		}
		
		/*RoomInfo roomInfo = new RoomInfo();
		roomInfo.setHotelId(hotelId);
		roomInfo.setRoomId(Integer.valueOf(roomId));
		List<RoomInfo> roomList = roomService.findRoomInfoAll(roomId,hotelId,"1");
		if (roomList != null && roomList.size() > 0) {
			RoomModel roomModel = new RoomModel();
			RoomInfo rf = roomList.get(0);
			BeanUtils.copyProperties(rf, roomModel);
			roomModel.setBookable(rf.getIsBookable());
			// 设施
			Map<String, String> facMap = new LinkedHashMap<>();
			Dict dict = new Dict();
			dict.setTableName("t_room_info");
			dict.setFieldName("facilities");
			if (rf.getFacilities() != null) {
				List<Dict> facDicts = this.dictService.findAllDicts(dict);
				String[] strs1 = rf.getFacilities().split(",");
				for (Dict fac : facDicts) {
					for (int i = 0; i < strs1.length; i++) {
						if (fac.getKeyy().equals(strs1[i].toString())) {
							facMap.put(fac.getKeyy(), fac.getValuee());
						}
					}
				}
			}
			roomModel.setFacilities(facMap);
			
			// 房策
			Map<String, String> policies = new HashMap<String, String>();
			if (rf.getPolicies() != null) {
				String[] strs3 = rf.getPolicies().split(",");
				dict.setFieldName("policies");
				List<Dict> polsDicts = this.dictService.findAllDicts(dict);
				for (Dict pol : polsDicts) {
					for (int i = 0; i < strs3.length; i++) {
						if (pol.getKeyy().equals(strs3[i].toString())) {
							policies.put(pol.getKeyy(), pol.getValuee());
						}
					}
				}
			}
			roomModel.setPolicies(policies);

			PictureInfo pic = new PictureInfo();
			pic.setTableName("t_room_info");
			pic.setTableId(roomId);
			pic.setType("2");
			List<PictureInfo> pics = this.picService.findPictures(pic);
			List<PictureModel> picsModel = new ArrayList<>();
			if(pics!=null) {
				for (int i = 0; i < pics.size(); i++) {
					PictureModel picModel = new PictureModel();
					picModel.setPicHref(pics.get(i).getPicHref());
					picModel.setPicUrl(pics.get(i).getPicUrl());
					picModel.setSort(pics.get(i).getSort());
					picsModel.add(picModel);
				}
				roomModel.setRoomPics(picsModel);
			}
			return RestResultGenerator.genSuccessResult(roomModel);
		}*/
	}

	/**
	 * 房态管理
	 * 
	 * @param hotelId
	 * @param roomId
	 * @param date
	 * @param bookable 0不可预定1可预定
	 * @param price    当日价格
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ApiOperation(value = "房态管理", notes = "房态管理（切换预定状态 :0不可预定1可预定）")
	@RequestMapping(value = "/switchBookable", method = RequestMethod.POST)
	public RestResult<String> manageRoomState(@RequestParam(required=true)String hotelId, @RequestParam(required=true)String roomId, 
			@RequestParam(required=true)String date, @RequestParam(required=true)String bookable,BigDecimal price) {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		try {
			Map<String,Object> map=new HashMap<>();
			map.put("roomId", roomId);
			map.put("hotelId", hotelId);
			map.put("endTime", sdf.parse(date));
			map.put("beginTime",null);
			List<RoomStatus> rss = this.roomStatusService.findRoomStatusAdmin(map);
			RoomStatus rs=new RoomStatus();
			rs.setHotelId(hotelId);
			rs.setRoomId(roomId);
			rs.setRoomDate(sdf.parse(date));
			if(price!=null) {
				rs.setPrice(price);	
			}
			if(bookable!=null) {
				rs.setIsBook(bookable);
			}
			if(rss!=null&&rss.size()>0) {
				rs.setId(rss.get(0).getId());
				this.roomStatusService.updateNotNull(rs);
			}else {
				this.roomStatusService.save(rs);
			}
			return RestResultGenerator.genSuccessResult("success");
		}catch (Exception e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult("invalid params");
		}
	}
	/**
	 * 获取房间列表及房态信息
	 * 
	 * @param orderId
	 * @return
	 */
	@ApiOperation(value = "房态信息展示（酒店管理端）", notes = "房态信息展示（酒店管理端）")
	@RequestMapping(value="/roomsAdmin",method = RequestMethod.GET)
	public RestResult<List<RoomModel>> RoomsAdmin(ServletRequest request,@RequestParam(required=true)String beginTimeStr) {
		try {
			String hotelId = (String) request.getAttribute("issuer");
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			Date beginTime=sdf.parse(beginTimeStr);
			Calendar  cale= Calendar.getInstance(); //得到日历
			cale.setTime(beginTime);//把当前时间赋给日历
			cale.add(Calendar.DAY_OF_MONTH, 1);  //设置为后一天
			Date endTime=cale.getTime();
			List<RoomModel> listRooms = this.roomService.RoomsAdmin(hotelId, beginTime, endTime);
			return RestResultGenerator.genSuccessResult(listRooms);
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult("error");
		}
	}
}
